package cn.cheegon.blog.common.interceptor;

import cn.cheegon.blog.common.log.WebLog;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc:统一日志处理切面
 * @Author: cheegon
 * @Date: Create in 2024/6/7  下午2:32
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    @Pointcut("execution(public * cn.cheegon.blog.controller.*.*(..))||execution(public * cn.cheegon.blog.*.controller.*.*(..)) ||execution(public * cn.cheegon.blog.*.*.controller.*.*(..))||@annotation(cn.cheegon.blog.common.log.Log)")
    public void webLog() {
    }


    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    /**
     * 在切点之前织入
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
       // HttpServletRequest request  = getRequest();
        //String urlStr = request.getRequestURL().toString();
      //  LOGGER.info("请求进入:{}", urlStr);
    }

    @AfterThrowing(value = "webLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        HttpServletRequest request = getRequest();
        MethodSignature methodSignature = getMethodSignature(joinPoint);
        Method method = methodSignature.getMethod();
        WebLog webLog = new WebLog();
        webLog.setStatus("异常");
        webLog.setUrl(request.getRequestURL().toString());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        Map<String, Object> logMap = new HashMap<>();
        logMap.put("status", webLog.getStatus());
        logMap.put("url", webLog.getUrl());
        logMap.put("method", webLog.getMethod());
        logMap.put("parameter", webLog.getParameter());
        LOGGER.error("{}", JSONUtil.parse(webLog).toString());
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        HttpServletRequest request  = getRequest();
        Object result = joinPoint.proceed();
        WebLog webLog = new WebLog();
        MethodSignature methodSignature = getMethodSignature(joinPoint);
        Method method = methodSignature.getMethod();
//        if (method.isAnnotationPresent(ApiOperation.class)) {
//            ApiOperation log = method.getAnnotation(ApiOperation.class);
//            webLog.setDescription(log.value());
//        }

        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        // webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        //  webLog.setIp(request.getRemoteUser());
        webLog.setStatus("成功");
        webLog.setUrl(request.getRequestURL().toString());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        // 获取Log注解
//        Log logAnnotation = getAnnotation(joinPoint);
//        if (logAnnotation!=null&&!StrUtil.isEmpty(logAnnotation.description())){
//            webLog.setDescription(logAnnotation.description());
//        }
        //   webLog.setSpendTime((int) (endTime - startTime));
//        webLog.setStartTime(startTime);
        // webLog.setUri(request.getRequestURI());
        Map<String, Object> logMap = new HashMap<>();
        logMap.put("status", webLog.getStatus());
        logMap.put("url", webLog.getUrl());
        logMap.put("method", webLog.getMethod());
        logMap.put("parameter", webLog.getParameter());
//        logMap.put("spendTime", webLog.getSpendTime());
        logMap.put("description", webLog.getDescription());
        LOGGER.info("{}", JSONUtil.parse(webLog).toString());
        return result;
    }
    /**
     * 获取方法上的注解
     */
//    private Log getAnnotation(ProceedingJoinPoint joinPoint) {
//        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
//        return method.getAnnotation(Log.class);
//    }
    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }

    private MethodSignature getMethodSignature(JoinPoint joinPoint) {
        return (MethodSignature) joinPoint.getSignature();
    }


    private HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }
}
